#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>

using std::cin;
using std::cout;
using std::endl;
using std::unordered_map;
using std::string;
using std::ifstream;
using std::ofstream;

#define ERROR_CHECK(cond, msg, cleanup) \
    do{ \
        if(cond) { \
            std::cerr << "Error:" << msg << "(" << __FILE__ << ":" << __LINE__ << ")" << std::endl; \
            cleanup; \
            return; \
        } \
    }while(0)

class Dictionary
{
public:
    void read(const std::string &filename);
    void store(const std::string &filename);
private:
    bool is_word(const string&);
    unordered_map<string, int> _dict;
};

bool Dictionary::is_word(const string& word){
    
    for(auto& ch : word){
        if(!isalpha(ch)) return false;
    }

    return true;
}

void Dictionary::read(const std::string &filename){
    // 1. 打开文件
    ifstream ifs(filename);
    ERROR_CHECK(!ifs.good(), "ifstream is not good", ifs.close());

    // 2. 存放单词
    string word;
    while(ifs >> word){
        //    while(ifs >> word){
        if(is_word(word)){
            ++_dict[word];
        }
    }

    // 3. 关闭文件
    cout << endl;
    ifs.close();
}

void Dictionary::store(const std::string &filename){
    // 1. 打开文件
    ofstream ofs(filename, std::ios::app);
    ERROR_CHECK(!ofs.good(), "ofs is not good", ofs.close());

    // 2. 遍历文件
    auto it = _dict.begin();
    while(it != _dict.end()){
        // 打印屏幕
        cout << it->first <<  " " 
             << it->second 
             << endl;
        
        // 写入文件
        ofs << it->first << " " 
            << it->second 
            << endl;
        ++it;
    }

    ofs.close();
}

int main(){
    Dictionary dict;

    dict.read("The_Holy_Bible.txt");
    dict.store("13_Statistic.txt");
}
